/**
 * Created by 小敏哥on 2017/3/8.
 */
import React, {Component} from 'react';
import {List, Toast} from 'antd-mobile';
import {connect} from 'react-redux';
import {getCheckDate, getCarInfo} from '../../actions/updateCarInfoAction';
import {getCalculation} from '../../actions/calculatorAction';
import DropDownBox from '../../components/updateCarInfo/dropDownBox';
import AlipayJSOperation from '../../utils/alipayJSOperation';
import style from './index.scss';
import SendCxytjMessage from '../../utils/sendCxytjMessage';
import DatePicker from 'react-mobile-datepicker';
import '../../../styles/datePickerAdapt.scss';

class CalculatorOfYearlyCheck extends Component {
    constructor(props) {
        super(props);
        this.computeAndGotoDetail = this.computeAndGotoDetail.bind(this);
        this.changeCheckDate = this.changeCheckDate.bind(this);
        this.getCurrentValidityDate = this.getCurrentValidityDate.bind(this);
        this.state = {
            registerDate: '请选择',
            validityDate: '请选择',//有效时间
            dateList: [],//有效期时间列表
            carId: props.params.carId ? props.params.carId : props.carList.cars[props.currentCarIndex].carId,//车辆id
            carNumber: props.params.carNumber ? props.params.carNumber : props.carList.cars[props.currentCarIndex].carNumber,//车牌
            carCode: '',//车辆code
            engineNumber: '',//引擎号码
            isOpenDatePicker: false,//是否显示日期选择器
        };
        //此处定义app返回键的回调函数
        /*window.cxyClickBack = () => {
            history.back();
        }*/
    }


    //获取最终的有效时间
    getCurrentValidityDate(index) {
        this.setState({
            validityDate: this.state.dateList[index].label,
            selectedIndex: index,
        });
    }

    formatDate(date) {
        if (date.getMonth) {
            let monthString = date.getMonth() + 1 < 10 ? ('0' + (date.getMonth() + 1).toString()) : (date.getMonth() + 1).toString();
            let dateString = date.getDate() < 10 ? ('0' + date.getDate().toString()) : date.getDate().toString();
            return date.getFullYear() + '-' + monthString + '-' + dateString;
        }
        return date;
    }

    getCarInfo() {
        this.props.dispatch(getCarInfo({carNumber: this.state.carNumber, carId: this.state.carId}, (result) => {
            this.setState({
                registerDate: result.registerDate ? new Date(result.registerDate) : this.state.registerDate,
                validityDate: result.checkDate ? result.checkDate : this.state.validityDate,
                carCode: result.carCode ? result.carCode : '',
                engineNumber: result.engineNumber ? result.engineNumber : '',
            });
            setTimeout(() => {
                this.state.registerDate && this.changeCheckDate(this.formatDate(this.state.registerDate), false);
            }, 0)
        }));
    }

    getDropDownIndex(data) {
        var now = new Date();
        var dateCache;
        for (var i = data.length - 1; i >= 0; i--) {
            dateCache = new Date(data[i].label);
            if (now - dateCache < 30 * 24 * 60 * 60 * 1000) {
                return i;
            }
        }
        return 0;
    }

    //获取数据后更新有效时间列表
    changeCheckDate(registerDate, init = true) {
        if(registerDate!='请选择') {
        this.props.dispatch(getCheckDate({registerDate: registerDate}, (result) => {
            var dateList = [];
            for (var i = 0; i < result.length; i++) {
                dateList.push({
                    value: i,
                    label: result[i].checkDate
                });
            }
            this.setState({
                dateList: dateList
            });
            init && this.getCurrentValidityDate(this.getDropDownIndex(dateList));
        }));
        }
    }

    //获取计算结果后跳转到年检信息页面
    computeAndGotoDetail() {
        if (this.state.registerDate == '请选择') {
            Toast.info("请选择注册日期！", 1);
            return;
        }
        if (this.state.validityDate == '请选择') {
            Toast.info("请选择校验有效期！", 1);
            return;
        }
        // let current = this.props.carList.cars[this.props.currentCarIndex];
        this.props.dispatch(getCalculation({
            carId: this.state.carId,
            carNumber: this.state.carNumber,
            registerDate: this.formatDate(this.state.registerDate),
            checkDate: this.state.validityDate,
            carCode: this.state.carCode,
            engineNumber: this.state.engineNumber,
        }, () => {
            this.context.router.push('/yearlyCheckDetail');
        }));
        SendCxytjMessage.sendMessage({eventId: 'Insepection_SaveandCheck'})
    }

    componentDidMount() {
        /*if (this.props.carList == undefined) {
         this.context.router.push('/');
         }
         else {*/
        this.getCarInfo();
        //隐藏标题栏右键
        AlipayJSOperation.setRightButtonStatus(false);
        AlipayJSOperation.setTitle('年检计算器');
        AlipayJSOperation.setBarColor('#2FB3FE');
        document.querySelector("title").innerHTML = "年检计算器";
        //  }
        SendCxytjMessage.sendMessage({eventId: 'Insepection_EnterCalculator'})
    }

    componentWillUnmount() {
        AlipayJSOperation.removeLeftButtonEvent();
    }

    showDropDrown() {
        if (this.state.registerDate == '请选择') {
            Toast.info("请选择注册日期！", 1);
        }
        else {
            DropDownBox.showComponent(true)
        }
    }

    render() {
        return <div className={style.calculatorContainer}>
            {/*<PageBar title="年检计算器"/>*/}
            <div className={style.tips}>{'请输入' + this.state.carNumber + '车辆的注册信息'}</div>
            <div className={style.calculatorMessage}>
                <List className="picker-list">

                    {/*<DatePicker
                        mode="date"
                        title="请选择日期"
                        extra="请选择"
                        onChange={(date) => {
                            this.changeCheckDate(date.format('YYYY-MM-DD'));
                            this.setState({registerDate: date});
                        }}
                        value={this.state.registerDate}
                    >
                        <List.Item arrow="horizontal">车辆注册日期</List.Item>
                    </DatePicker>*/}
                    <List.Item arrow="horizontal"
                               extra={this.state.registerDate == '请选择' ? this.state.registerDate : this.formatDate(this.state.registerDate)}
                               onClick={() => {
                                   this.setState({
                                       isOpenDatePicker: true
                                   });
                               }}>车辆注册日期</List.Item>
                    <List.Item extra={this.state.validityDate} arrow="horizontal" onClick={() => {
                        this.showDropDrown();
                    }}>检验有效期至</List.Item>
                </List>
            </div>
            <div className={style.buttonContainer}>
                <button onClick={this.computeAndGotoDetail}>保存并计算</button>
            </div>
            <article className={style.calculatorWarnning}>
                <div className={style.warningTitle}>
                    <div className={style.titleLine}></div>
                    <h1>年检条件计算说明</h1>
                    <div className={style.titleLine}></div>
                </div>
                <p>
                    1、输入准确的车辆信息，系统会智能计算出车辆的年检状态，以及下一次年检的类型。如果进入预约周期，系统还能自动提醒您需要准备哪些资料，该如何办理。如果一不小心逾期，系统还能协助您如何尽量避免损失。
                </p>
                <p>
                    2、本计算方式只适用于7座以下的蓝牌小轿车。
                </p>
            </article>
            <DropDownBox data={this.state.dateList} selectedIndex={this.state.selectedIndex}
                         onChange={(index) => {
                             this.getCurrentValidityDate(index)
                         }}></DropDownBox>
            <DatePicker
                value={this.state.registerDate != '请选择' ? this.state.registerDate : new Date()}
                isOpen={this.state.isOpenDatePicker}
                theme="ios"
                dateFormat={['YYYY年', 'MM月', 'DD日']}
                onSelect={(date) => {
                    this.changeCheckDate(this.formatDate(date));
                    this.setState({
                        registerDate: date,
                        isOpenDatePicker: false
                    });
                }}
                onCancel={() => {
                    this.setState({
                        isOpenDatePicker: false
                    });
                }}/>
        </div>
    }
}

//react router跳转时使用了context，此处需要显式声明
CalculatorOfYearlyCheck.contextTypes = {
    router: React.PropTypes.object.isRequired
};

function mapStateToProps(state) {
    return Object.assign({}, state.homeInfo);
}

export default connect(mapStateToProps)(CalculatorOfYearlyCheck)
